/*
 * msgping.c
 *
 * Copyright 2012 Kamil Cukrowski <kamil@dyzio.pl>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation version 2.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */
#define MSGAMETER_VERSION 3.1.3
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <arpa/inet.h>

#include <msgserv.h>

#define TEMPFILE "/tmp/tmpmsgping.tmp"



const char const hosts[][16] ={
	"194.11.24.77",
	"77.253.214.76",
	"77.252.226.137",
	"10.3.1.61",
};
const char const hosts_names[][10] = {
	"dyzio",
	"biurek",
	"sojka",
	"ustro",
};



in_addr_t server_ip =  { 16777343 }; // 127.0.0.1
int debug = 0;
int refresh_time = 60;
int sockfd;

void safe_exit()
{
	msglcd_disconnect(sockfd);
        exit(0);
}

#define fatal(format, ...) \
do {\
        PERROR(format, ##__VA_ARGS__);\
        safe_exit();\
} while (0)

#define perror(...) PERROR( __VA_ARGS__ )

void sig_hup (int param) {
	PDEBUG("Signal received. Going down");
	safe_exit();
}

void parse_cmd(int argc, char *argv[])
{
	int c=0;
	opterr=0;
	while ( (c = getopt(argc, argv, "hdr:i:")) != -1 )
	switch (c) {
	case 'h':
		printf("msgping: pings list of hosts and writes if their up\n"
			"msgping [-d] [-r] [-i] \n"
		);
		exit(0);
	case 'd':
		debug++;
		break;
	case 'r':
		refresh_time=atoi(optarg);
		break;
	case 'i':
		server_ip=inet_addr(optarg);
		break;
	}
}

int check_alive(const char str[])
{
	char cmd[] = { "ping -c 1 -w 1                              | grep received | awk '{print $4}' > " TEMPFILE };
	FILE *tmp;
	char ret;
	char *pnt;

	in_addr_t ip = inet_addr(str);
	pnt = inet_ntoa(*(struct in_addr *)&ip);

	//printf("%lld :: ", (long long int)ip);

	sprintf(cmd+15, "%s",  pnt);
	cmd[15+strlen(pnt)]=' ';

	if ( system(cmd) == -1 ) {
		printf("system");
		return -1;
	}

	tmp = fopen(TEMPFILE, "r");
	if ( tmp == NULL ) {
		printf("fopen: %s ", strerror(errno));
		return -1;
	}

	if ( fread(&ret, 1, 1, tmp) == -1 ) {
		printf("fread");
		return -1;
	}
	ret -= '0';

	fclose(tmp);

	if ( remove( TEMPFILE ) == -1 ) {
		perror("remove");
		return -1;
	}

	return ret ? 1 : 0;
}

static void handle_msglcd_handle_server(const int lcd_sock) 
{
	int i;
	switch ( (i = msglcd_handle_server(lcd_sock)) ) {
	case -5:
	case -1:
		fatal("Strange error occured %d ", i);
	case -4:
		fatal("Server closed the connection. %d ", i);
	case -6:
		fatal("server sended error messege %d", i);
	case -2:
		fatal("Server closed the connection without sending exit mesg. %d ", i);
	case -3:
		fatal("my mesg has somth wrong %d ", i);
	}
}

static void handle_msg_updat(const int sockfd, const char nr, const char pri, const char *mesg, const int len) 
{
	int i;
	i = msglcd_updat(sockfd, nr, pri, mesg, len);
	if ( i == 0 ) return;
	fatal("could not update mesg. msglcd_updat returned: %d", i);
}

int main(int argc, char *argv[])
{	
	const int hosts_num = sizeof(hosts)/sizeof(*hosts);
	int i;
	char mesg[41];
	char tmp[41];
	
	parse_cmd(argc, argv);
	
	if (!server_ip) {
		fprintf(stderr, "Please give msgsrv ip address.\n");
		safe_exit();
	}
	
	signal(SIGHUP,sig_hup);
	signal(SIGQUIT,sig_hup);
	signal(SIGTERM,sig_hup);
	signal(SIGINT,sig_hup);
	
	sockfd = msglcd_connect(server_ip);
	if (sockfd < 0) fatal("Could not connect to lcd server %d \n", sockfd);
	
	if ( debug <= 0 ) {
		#define MY_NAME "msgping"
		openlog(MY_NAME,LOG_PID,LOG_DAEMON);
		syslog(LOG_INFO,"Startup  succeeded.");
	}
	
	for(;;) {
		mesg[0] = '\0';
	
		for(i=0; i<hosts_num; i++) {
			snprintf(tmp, 40, "%s %5s:%1d ", mesg, hosts_names[i], check_alive(hosts[i]));
			memcpy(mesg, tmp, 41*sizeof(char));
		}
		
		if ( strlen(mesg) < 40 ) {
			for(i=strlen(mesg); i<41; i++)
				mesg[i] = ' ';
		}
				
		
		if ( debug ) {
			printf(" %s \n", mesg);
		}
		
		handle_msg_updat(sockfd, 0, MSG_DEBUG, mesg, 40);
		handle_msglcd_handle_server(sockfd);
		
		sleep(refresh_time);
	}
		
	return 0;
}
